//=====================================================================
// 让 zsh 的历史记录可读
//=====================================================================
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//---------------------------------------------------------------------
void readhist();
void writehist();
void usage();
static int ismeta(unsigned char ch);
//---------------------------------------------------------------------
int main(int argc, char** argv){
  if(argc == 1)
    readhist();
  else if(argc == 2){
    if(!strcmp(argv[1], "read"))
      readhist();
    else if(!strcmp(argv[1], "write"))
      writehist();
    else
      usage();
  }else
    usage();
  return 0;
}
void readhist(){
  unsigned char c, d;
  int change = 0;
  while(read(0, &c, 1)){
    if(c != 0x83){
      if(change){
	d = c ^ 32;
      }else
	d = c;
      write(1, &d, 1);
      change = 0;
    }else
      change = 1;
  }
}
void writehist(){
  unsigned char c, d;
  while(read(0, &c, 1)){
    if(ismeta(c)){
      d = 0x83;
      write(1, &d, 1);
      d = c ^ 32;
      write(1, &d, 1);
    }else
      write(1, &c, 1);
  }
}
void usage(){
  fprintf(stderr, "Usage: zhist [read|write]\n"
      "\tzhist reads from stdin and outputs to stdout, "
      "with the content changes\nto be read by human being "
      "or by the zsh program.\n");
  exit(1);
}
static int ismeta(unsigned char ch){
  return (ch > 0x83 && ch < 0x9e)
    || ch == 0xa0 || ch == 0x83 || ch == 0;
}
//====================================================================
